package org.example.service.ack;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.stream.IntStream;

/**
 * @author Tang
 * @classname DirectSender
 * @description [  ]
 * @date 2023/4/10 22:06
 */
//@Component
public class AckSender implements CommandLineRunner {

    @Resource
    RabbitTemplate rabbitTemplate;

    @Override
    public void run(String... args) throws Exception {

        final Message infoMsg = MessageBuilder
                .withBody("info msg".getBytes(StandardCharsets.UTF_8))
                .setContentType(MessageProperties.CONTENT_TYPE_BYTES)
                .build();

        this.rabbitTemplate.setConfirmCallback(new DataCallback());
        this.rabbitTemplate.setReturnCallback(new DataCallback());

        IntStream
                .range(0,1)
                .forEach((index) -> {
                    rabbitTemplate.convertAndSend("test-ack-exchange",
                            "test-ack-key", "info msg" + index);
                });
    }


    public static class DataCallback implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {

        /**
         * 交换机确认：ConfirmCallback方法
         * @param correlationData
         * @param ack
         * @param cause
         */
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            System.out.println("===============confirm===============");
            System.out.println("correlationData:" + correlationData);
            System.out.println("ack:" + ack);
            System.out.println("cause:" + cause);
            System.out.println("===============confirm===============");
        }

        /**
         * 队列确认：ReturnCallback方法 确定消息是否送达到队列
         * @param message
         * @param replyCode
         * @param replyText
         * @param exchange
         * @param routingKey
         */
        @Override
        public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
            System.out.println("============returnedMessage==================");
            System.out.println("message:" + message.toString());
            System.out.println("replyCode:" + replyCode);
            System.out.println("exchange:" + exchange);
            System.out.println("routingKey:" + routingKey);
            System.out.println("============returnedMessage==================");
        }
    }

}
